package grpc_proxy_middleware

import (
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"github.com/pkg/errors"
	"google.golang.org/grpc"
	"log"
	"time"
)

// GRPC QPS 统计
func GRPCFlowCountModeMiddleware(service *dao.ServiceDetail) func(srv interface{}, ss grpc.ServerStream,
	info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
	return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
		// 统计项： 1 全站 2 服务 3 租户
		// 全站统计器
		totalCounter, err := public.FlowCounterHandler.GetCounter(public.FlowTotal)
		if err != nil {
			return errors.New("【GRPC】获取全站统计器失败：" + err.Error())
		}
		totalCounter.Increase()
		dayCount, _ := totalCounter.GetDayData(time.Now())
		log.Printf("【GRPC】全站统计 qps:%v dayCount:%v", totalCounter.QPS, dayCount)
		// 服务统计器
		serviceCounter, err := public.FlowCounterHandler.GetCounter(public.FlowServicePrefix + service.Info.ServiceName)
		if err != nil {
			return errors.New("【GRPC】获取服务统计器失败：" + err.Error())
		}
		serviceCounter.Increase()
		dayServiceCount, _ := serviceCounter.GetDayData(time.Now())
		log.Printf("【GRPC】服务统计 qps:%v dayCount:%v", serviceCounter.QPS, dayServiceCount)
		if err := handler(srv, ss); err != nil {
			log.Printf("【GRPC】RPC failed with error %v\n", err)
		}
		return nil
	}
}
